package com.anlogic.sdk.app.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;

import com.anlogic.sdk.app.model.ApplicationProject;
import com.anlogic.sdk.app.model.ApplicationProjectNature;
import com.anlogic.sdk.app.model.IApplicationProject;
import com.anlogic.sdk.bsp.model.IPlatformProject;
import com.anlogic.sdk.utils.LogUtils;

public class ApplicationUtils {
	private static Logger logger = LogUtils.getLogger(ApplicationUtils.class);

	public static List<IApplicationProject> getApplicationProjectsInWorkspace() {
		return getApplicationProjectsInWorkspace(ResourcesPlugin.getWorkspace().getRoot());
	}

	public static List<IApplicationProject> getApplicationProjectsInWorkspace(IWorkspaceRoot root) {
		ArrayList<IApplicationProject> projList = new ArrayList<IApplicationProject>();
		for (IProject project : root.getProjects()) {
			try {
				if (ApplicationProjectNature.isApplicationProject(project)) {
					IApplicationProject proj = new ApplicationProject(project);
					proj.restoreMetaData();
					projList.add(proj);
				}
			} catch (CoreException e) {
				logger.error("Get application projects Error {}", e.getMessage());
			}
		}

		return projList;
	}

	public static IApplicationProject getApplicationProject(String projName) {
		IApplicationProject appProj = null;
		for (IApplicationProject proj : getApplicationProjectsInWorkspace()) {
			if (proj.getName().equals(projName)) {
				appProj = proj;
			}
		}
		return appProj;
	}

	public static IApplicationProject getAppProjectFromIProject(IProject project) {
		IApplicationProject appProj = null;
		try {
			if (ApplicationProjectNature.isApplicationProject(project)) {
				appProj = new ApplicationProject(project);
				appProj.restoreMetaData();
			}
		} catch (CoreException e) {
			logger.error("Get application project Error {}", e.getMessage());
		}
		return appProj;
	}
	
	public static IPlatformProject getPlatformFromApp(String projName) {
		IPlatformProject bspProj = getApplicationProject(projName).getBspProj();
		return bspProj;
	}
}
